<template>
    <div class="attorney">
        <a-tree v-if="attorney.departTree.length > 0" v-model:checked-keys="attorney.checkedKeys" :tree-data="attorney.departTree" :field-names="attorney.fieldNames" default-expand-all block-node checkable check-strictly :selectable="false" @check="onCheck" />
    </div>
</template>
<script setup>
import { reactive } from 'vue'
import { getEnableMenu } from '/@/api/System/Menu'
import { getMenuIds } from '/@/api/System/Role'
import { SUCCESS_CODE } from '@iframe/tools/axios/axios'
import TreeUtils from '@iframe/tools/utils/TreeUtils'

const attorney = reactive({
    roleId: null,
    departTree: [],
    checkedKeys: {
        checked: [],
        halfChecked: []
    },
    fieldNames: {
        title: 'name',
        key: 'id',
        children: 'children'
    }
})

const initMenuList = () => {
    getEnableMenu().then(result => {
        if (result.code === SUCCESS_CODE) {
            attorney.departTree = TreeUtils.generateTreeData(result.data) || []
        }
    })
}

const setRoleId = roleId => {
    attorney.roleId = roleId
    getMenuIds({ id: roleId }).then(result => {
        if (result.code === SUCCESS_CODE) {
            attorney.checkedKeys.checked = result.data
            console.log(attorney.checkedKeys.checked)
        }
    })
}

const getForm = () => {
    return { id: attorney.roleId, menuIds: attorney.checkedKeys.checked }
}
const onCheck = (checkedKeys, e) => {
    if (e.checked) {
        checkParent(checkedKeys, e.node.parentPath)
        checkChildren(checkedKeys, e.node.children)
    } else {
        unCheckChildren(checkedKeys, e.node.children)
    }
}
const unCheckChildren = (checkedKeys, children) => {
    if (children && children.length > 0) {
        for (let i = 0; i < children.length; i++) {
            addOrRemove(checkedKeys, children[i].id, false)
            unCheckChildren(checkedKeys, children[i].children)
        }
    }
}
const checkChildren = (checkedKeys, children) => {
    if (children && children.length > 0) {
        for (let i = 0; i < children.length; i++) {
            addOrRemove(checkedKeys, children[i].id, true)
            checkChildren(checkedKeys, children[i].children)
        }
    }
}
const checkParent = (checkedKeys, parentPath) => {
    if (parentPath) {
        const parentIds = parentPath.split(',')
        parentIds.forEach(item => {
            addOrRemove(checkedKeys, item, true)
        })
    }
}
/**
 * 添加或移除
 * @param checkedKeys
 * @param id
 * @param addRemove
 */
const addOrRemove = (checkedKeys, id, addRemove) => {
    if (addRemove) {
        if (!checkedKeys.checked.includes(id)) {
            checkedKeys.checked.push(id)
        }
    } else {
        checkedKeys.checked = checkedKeys.checked.filter(item => item !== id)
    }
}

initMenuList()
defineExpose({ setRoleId, getForm })
</script>
